
from time           import time

class TimeStat(object):
    def __init__(self):
        self.tsdata = {}
        
    def __call__(self, func, name=None):
        name = func.__name__ if not name else name
        self.tsdata[name] = (0, 0, 0, 0)
        def wrapper(*args, **kw):
            ts = time()
            try:
                func(*args, **kw)
            except:
                from canvas3d import log
                log.exception("Error in calling func from time stat wrapper")
            telapsed = time() - ts
            num, mn, tot, mx = self.tsdata[name]
            mn = min(mn, telapsed)
            tot += telapsed
            mx = max(mx, telapsed)
            num += 1
            self.tsdata[name] = (num, mn, tot, mx)
        return wrapper
    
    def printStats(self):
        width = (5*11 + 38)
        patternd = '# %-34s # %8d # %8.5f # %8.5f # %8.5f # %8.3f #'
        patternh = '# %-34s # %8s # %8s # %8s # %8s # %8s #'
        headers = ('Function name', 'calls', 'min', 'avg', 'max', 'total')
        print '#' + '-' * (width - 2) + '#'
        print patternh%headers
        print '#' + '-' * (width - 2) + '#'
        for key in sorted(self.tsdata.keys()):
            data = self.tsdata[key]
            key = key[:30]
            num, mn, tot, mx = data
            avg = tot/num if num > 0 else 0
            mn *= 1000
            avg *= 1000
            mx *= 1000
            print patternd%(key, num, mn, avg, mx, tot)
        print '#' + '-' * (width - 2) + '#'

timestat = TimeStat()
